﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
using MedReg.Classes;
using MedReg.Utils;

namespace MedReg
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeBackgroundWorker();
        }


       private void button1_Click(object sender, EventArgs e)
        {
           /* 
           DialogResult res = openFileDialog1.ShowDialog(this);
            if (res == DialogResult.OK)
            {
                
                string fn = openFileDialog1.FileName;
                var fs = new FileStream(fn, FileMode.Open);

                Console.WriteLine("Classes");
                Console.ReadLine();
                fs.Position = 0;
                var xdocc = new XmlSerializer(typeof (ArrayOfStaffEnrty));
                var StaffEntryColc = (ArrayOfStaffEnrty) xdocc.Deserialize(fs);

                fs.Close();
                
                foreach (Classes.StaffEntry staffEntry in StaffEntryColc)
                {
                    //   Console.WriteLine(staffEntry.UZ.ID); //Error!!!!!!!!!!!! There is no LPU
                }
                Console.WriteLine(StaffEntryColc.Count);

                var objList = new List<Classes.StaffEntry>(StaffEntryColc.Cast<Classes.StaffEntry>());


                var mdb = new MedregDBDataContext();
                var sSub = new Classes.Subdivision();
                var sNom = new Classes.Nomenclature();
                var sPos = new Classes.Post();
                var sUz = new Classes.LPU();
                var sLev = new Classes.Level();
                var sSTE = new Classes.StaffEntry();
                
                
                mdb.Log = Console.Out;

                var lpu = new LPU();
                //lpu.ImportList(sUz.getLPUList(StaffEntryColc));

                var ste = new StaffEntry();
                ste.ImportList(StaffEntryColc);

                //foreach (var staffEntry in sSTE.getStaffEntryList(StaffEntryColc))
                // {
                //    Console.WriteLine(staffEntry.UZ.ID + " " + staffEntry.Branch.ID + " " + staffEntry.Quantity);
                // }



                //mdb.LPU.InsertAllOnSubmit(sUz.getLPUList(StaffEntryColc));
                //mdb.Subdivision.InsertAllOnSubmit(sSub.getSubdivisionList((StaffEntryColc)));
                //mdb.Post.InsertAllOnSubmit(sPos.getPostList(StaffEntryColc));
                //mdb.Level.InsertAllOnSubmit(sLev.getLevelList(StaffEntryColc));
                //mdb.Nomenclature.InsertAllOnSubmit(sNom.getNomeclatureList(StaffEntryColc));
                //mdb.SubmitChanges();

                //sSub.ImportList(sSub.getSubdivisionList((StaffEntryColc)));
                //sNom.ImportList(sNom.getNomeclatureList(StaffEntryColc));
                //sPos.ImportList(sPos.getPostList(StaffEntryColc));
                //sLev.ImportList(sLev.getLevelList(StaffEntryColc));
                //sUz.ImportList(sUz.getLPUList(StaffEntryColc));
                //  sSTE.ImportList(sSTE.getStaffEntryList(StaffEntryColc));
                //mdb.SubmitChanges();

                //mdb.StaffEntry.InsertAllOnSubmit(sSTE.getStaffEntryList((StaffEntryColc)));););))

                //Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@@");



            }
           */
        }

        
        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult res = openFileDialog1.ShowDialog(this);
            if (res == DialogResult.OK)
            {
                string fn = openFileDialog1.FileName;
                var XML = new ImportXML();
                XML.ImportFile(fn);

                // var db = new medgerDataContext();
                // db.Subdivision.InsertOnSubmit(StaffEntryCol[1].Subdivision);
                // db.SubmitChanges();
            }
        }
        
        //public void AddToLogBox (string msg)
        //{
        //    LogBox.Items.Add(msg);
        //}

        delegate void SetTextCallback(string text);

        public void AddToLogBox(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.LogBox.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(AddToLogBox);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.LogBox.Items.Add(text);
            }
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            DialogResult res = folderBrowserDialog1.ShowDialog(this);
            if (res == DialogResult.OK)
            {
                
                LogBox.Items.Clear();
                this.startAsyncButton.Enabled = false;
                
                // Enable the Cancel button while 
                // the asynchronous operation runs.
                this.cancelAsyncButton.Enabled = true;
                
                string dir = folderBrowserDialog1.SelectedPath;
                // Start the asynchronous operation.
                backgroundWorker1.RunWorkerAsync(dir);
            }

            

        }
        //public int ProgressBarMax
        //{
        //    set { progressBar1.Maximum = value;}
        //}


        //delegate void SetProgressBarMaximumCallback(int value);
        /*
        public void ProgressBarMax(int value)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.progressBar1.InvokeRequired)
            {
                SetProgressBarMaximumCallback d = new SetProgressBarMaximumCallback(ProgressBarMax);
                this.Invoke(d, new object[] { value });
            }
            else
            {
                this.progressBar1.Maximum = value;
            }
        }

        */

        //public void ProgressBarStep ()
        //{
        //    progressBar1.PerformStep();
        //}

        
        private void InitializeBackgroundWorker()
        {
            backgroundWorker1.DoWork +=
                new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler(
            backgroundWorker1_RunWorkerCompleted);
            backgroundWorker1.ProgressChanged +=
                new ProgressChangedEventHandler(
            backgroundWorker1_ProgressChanged);
        }

        private void backgroundWorker1_DoWork(object sender,
           DoWorkEventArgs e)
        {
            // Get the BackgroundWorker that raised this event.
            BackgroundWorker worker = sender as BackgroundWorker;

            // Assign the result of the computation
            // to the Result property of the DoWorkEventArgs
            // object. This is will be available to the 
            // RunWorkerCompleted eventhandler.
            var XML = new ImportXML();
            XML.ImportDir((string)e.Argument, worker, e);
            
        }

        // This event handler deals with the results of the
        // background operation.
        private void backgroundWorker1_RunWorkerCompleted(
            object sender, RunWorkerCompletedEventArgs e)
        {
            // First, handle the case where an exception was thrown.
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                // Next, handle the case where the user canceled 
                // the operation.
                // Note that due to a race condition in 
                // the DoWork event handler, the Cancelled
                // flag may not have been set, even though
                // CancelAsync was called.
                AddToLogBox("Canceled");
            }
            else
            {
                // Finally, handle the case where the operation 
                // succeeded.
                //AddToLogBox(e.Result.ToString());
                AddToLogBox("Done!");
            }

            
            // Enable the Start button.
            startAsyncButton.Enabled = true;

            // Disable the Cancel button.
            cancelAsyncButton.Enabled = false;
        }

        // This event handler updates the progress bar.
        private void backgroundWorker1_ProgressChanged(object sender,
            ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            
        }

        private void cancelAsyncButton_Click(object sender, EventArgs e)
        {
            // Cancel the asynchronous operation.
            this.backgroundWorker1.CancelAsync();

            // Disable the Cancel button.
            cancelAsyncButton.Enabled = false;
         
        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            DialogResult res = folderBrowserDialog1.ShowDialog(this);
            if (res == DialogResult.OK)
            {

                LogBox.Items.Clear();
                string dir = folderBrowserDialog1.SelectedPath;
                (new FixReport()).LoadReports(dir);
                
            }
            
            
        }

        
    }
}